@echo off
chcp 65001 >nul
echo 飞帆每日任务执行脚本
echo ====================

:: 切换到bat文件夹的上级目录（feifan-api目录）
cd /d "%~dp0.."

:: 设置日志文件
set LOG_FILE=%~dp0..\logs\daily-task.log
if not exist "%~dp0..\logs" mkdir "%~dp0..\logs"

:: 记录执行时间
echo [%date% %time%] 开始执行每日任务 >> "%LOG_FILE%"

:: 检查服务是否运行
echo [%date% %time%] 检查服务状态... >> "%LOG_FILE%"
curl -s http://localhost:3333/get-token >nul 2>&1
if errorlevel 1 (
    echo [%date% %time%] 服务未运行，正在启动服务... >> "%LOG_FILE%"
    call "%~dp0start-feifan.bat"
    timeout /t 10 /nobreak >nul
    
    :: 再次检查服务
    curl -s http://localhost:3333/get-token >nul 2>&1
    if errorlevel 1 (
        echo [%date% %time%] 错误：服务启动失败，任务终止 >> "%LOG_FILE%"
        exit /b 1
    )
    echo [%date% %time%] 服务启动成功 >> "%LOG_FILE%"
)

:: 执行每日任务
echo [%date% %time%] 执行用户mmwang37的每日任务... >> "%LOG_FILE%"
curl -s "http://localhost:3333/run-job?userName=mmwang37" >> "%LOG_FILE%" 2>&1

if errorlevel 1 (
    echo [%date% %time%] 错误：任务执行失败 >> "%LOG_FILE%"
) else (
    echo [%date% %time%] 任务执行完成 >> "%LOG_FILE%"
)

echo [%date% %time%] 每日任务执行结束 >> "%LOG_FILE%"
echo. >> "%LOG_FILE%"
